package com.lonely.base;

import com.google.common.base.Stopwatch;
import lombok.SneakyThrows;
import org.apache.calcite.adapter.jdbc.JdbcSchema;
import org.apache.calcite.jdbc.CalciteConnection;
import org.apache.calcite.schema.Schema;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @date: 2022-11-28 10:40
 * @author: ztkj-hzb
 * @description: jdbc schema
 **/
public class JdbcSchemaTest {


    @SneakyThrows
    public static void main(String[] args) {
        final Stopwatch started = Stopwatch.createStarted();
        Class.forName("org.apache.calcite.jdbc.Driver");
        Properties info = new Properties();
        info.setProperty("lex", "MYSQL");
        info.setProperty("caseSensitive", "false");
        Connection connection = DriverManager.getConnection("jdbc:calcite:", info);
        CalciteConnection calciteConnection = connection.unwrap(CalciteConnection.class);
        SchemaPlus rootSchema = calciteConnection.getRootSchema();

        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/rpasys");
        dataSource.setUsername("root");
        dataSource.setPassword("duguxiaobiao");
        Schema schema = JdbcSchema.create(rootSchema, "hr", dataSource, null, null);
        rootSchema.add("hr", schema);
        Statement statement = calciteConnection.createStatement();
        ResultSet resultSet = statement.executeQuery(
                "select d.deptno, min(e.id)\n"
                        + "from hr.emps as e\n"
                        + "join hr.depts as d\n"
                        + "  on e.deptno = d.deptno\n"
                        + "group by d.deptno\n"
                        + "having count(*) > 1");

        System.out.println(ResultSetUtil.resultString(resultSet));

        resultSet.close();
        statement.close();
        connection.close();


        final Stopwatch stop = started.stop();
        final long elapsed = stop.elapsed(TimeUnit.MILLISECONDS);
        System.out.println(elapsed+"ms");
    }


}
